package com.wangdao.wechatmall.controller.wx;

import com.wangdao.wechatmall.bean.pojo.Storage;
import com.wangdao.wechatmall.bean.vo.admin.BaseRespVo;
import com.wangdao.wechatmall.bean.vo.admin.FileUploadVO;
import com.wangdao.wechatmall.mapper.StorageMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Description: 存储Controller类
 * @Author: JK、Xinhao Yi
 * @Date: create in 2021/7/9 21:03
 */
@RestController
@RequestMapping("wx/storage")
public class WXStorageController {
    @Value("${upload.path}")
    String fileUploadPath;

    @Value("${mapping.path}")
    String mappingPath;

    @Value(("${domain}"))
    String domain;

    @Autowired
    StorageMapper storageMapper;

    @SneakyThrows
    @PostMapping("upload")
    public BaseRespVo upload(MultipartFile file) {
        File fileStorageDirectory = new File(fileUploadPath);
        if (!fileStorageDirectory.exists()) {
            fileStorageDirectory.mkdirs();
        }
        UUID uuid = UUID.randomUUID();
        String name = file.getOriginalFilename();
        String type = file.getContentType();
        String key = uuid + "." + type.substring(type.indexOf("/") + 1);
        Integer size = ((int) file.getSize());
        String url = domain + mappingPath + key;

        Date date = new Date();
        String currentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

        // 接收文件
        File fileToStorage = new File(fileUploadPath + key);
        //上传文件
        file.transferTo(fileToStorage);

        //插入数据库
        Storage storage = new Storage(null, key, name, type, size, url, currentDate, currentDate,0);
        int affectedRows = storageMapper.insertSelective(storage);

        FileUploadVO fileUploadVO = new FileUploadVO(storage.getId(), key, name, type, size, url, currentDate, currentDate);
        if (affectedRows == 1) {
            return BaseRespVo.ok(fileUploadVO);
        }
        return BaseRespVo.fail();
    }
}
